package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/honwee/awm/internal/service"
	"net/http"
	"strings"
)

type AuthMiddleware struct {
	projectUserService *service.ProjectUserService
}

func NewAuthMiddleware(projectUserService *service.ProjectUserService) *AuthMiddleware {
	return &AuthMiddleware{
		projectUserService: projectUserService,
	}
}

// APIKeyAuth API Key认证中间件
func (m *AuthMiddleware) APIKeyAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		authHeader := c.GetHeader("Authorization")
		if authHeader == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "missing API key"})
			c.Abort()
			return
		}

		// 检查Bearer前缀
		const prefix = "Bearer "
		if !strings.HasPrefix(authHeader, prefix) {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid API key format"})
			c.Abort()
			return
		}

		// 提取API Key
		apiKey := strings.TrimPrefix(authHeader, prefix)
		if apiKey == "" {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "missing API key"})
			c.Abort()
			return
		}

		// 验证API Key
		projectUser, err := m.projectUserService.ValidateAPIKey(apiKey)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid API key"})
			c.Abort()
			return
		}

		// 将项目用户信息存储到上下文中
		c.Set("project_user", projectUser)
		c.Set("user_id", projectUser.UserID)
		c.Next()
	}
}
